﻿using System.Linq;
using Dapper;
using ML.Entity;
using ML.IRepository;

namespace ML.Repository
{
    public class InvitationProfitRepository: DBFactory, IInvitationProfitRepository
    {
        public InvitationProfitEntity GetById(string id)
        {
            const string sql = @"SELECT * FROM ml_invitationprofit WHERE Id=@Id";
            using (_db)
            {
                return _db.Query<InvitationProfitEntity>(sql, new { @Id=id}).FirstOrDefault();
            }
        }

        public bool Add(InvitationProfitEntity entity)
        {
            const string sql = @"INSERT INTO ml_invitationprofit(Id,UserId,InvitationCount,SuccessCount) VALUES (@Id,@UserId,@InvitationCount,@SuccessCount);";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Update(InvitationProfitEntity entity)
        {
            const string sql = @"UPDATE ml_invitationprofit Set Id=@Id,UserId=@UserId,InvitationCount=@InvitationCount SuccessCount=@SuccessCount  WHERE Id=@Id";
            using (_db)
            {
                if (_db.Execute(sql, entity) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool Delete(InvitationProfitEntity entity)
        {
            throw new System.NotImplementedException();
        }

        public bool Delete(string id)
        {
            throw new System.NotImplementedException();
        }

        public bool UpdataInvitationCountByUserId(int invitationCount, string userId)
        {
            const string sql = @"UPDATE ml_invitationprofit Set InvitationCount=@InvitationCount WHERE UserId=@UserId";
            using (_db)
            {
                if (_db.Execute(sql, new { @InvitationCount= invitationCount, @UserId=userId }) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public bool UpdataSuccessCountCountByUserId(int successCount, string userId)
        {
            const string sql = @"UPDATE ml_invitationprofit Set SuccessCount=@SuccessCount WHERE UserId=@UserId";
            using (_db)
            {
                if (_db.Execute(sql, new { @SuccessCount = successCount, @UserId = userId }) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public InvitationProfitEntity GetByUserId(string userId)
        {
            const string sql = @"SELECT * FROM ml_invitationprofit WHERE UserId=@UserId";
            using (_db)
            {
                return _db.Query<InvitationProfitEntity>(sql, new { UserId = userId }).FirstOrDefault();
            }
        }
    }
}